"use client";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Avatar, Button, Card, Col, Divider, Empty, Flex, Input, List, message, Modal, Row, Skeleton, Space, Tooltip, Typography } from "antd";
import { useSelector } from "react-redux";
import type { RootState } from "@/stores";
import { addUsingPost, deleteUsingPost, listPageUsingPost } from "@/api/questionCommentController";
import { DeleteOutlined, MessageOutlined, SendOutlined } from "@ant-design/icons";
import type { TextAreaRef } from "antd/es/input/TextArea";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import zhCN from "dayjs/locale/zh-cn";
import "./index.css";

dayjs.extend(relativeTime);
dayjs.locale(zhCN);

export interface CommentSectionProps {
    /** 题目 ID（必填） */
    questionId: number;
    /** 每页大小 */
    pageSize?: number;
}

/**
 * 题目评论区组件
 * 功能：
 * - 登录用户可发表评论
 * - 仅可删除自己的评论
 * - 支持评论的二级回复
 * - 未登录用户不可评论，显示引导登录
 */
const CommentSection: React.FC<CommentSectionProps> = ({ questionId, pageSize = 10 }) => {
    const loginUser = useSelector((state: RootState) => state.loginUser);
    const isLoggedIn = useMemo(() => !!loginUser?.id && loginUser.userRole && loginUser.userRole !== "not_login", [loginUser]);

    const [loading, setLoading] = useState<boolean>(false);
    const [submitting, setSubmitting] = useState<boolean>(false);
    const [replySubmittingId, setReplySubmittingId] = useState<number | null>(null);
    const [data, setData] = useState<API.QuestionCommentVO[]>([]);
    const [total, setTotal] = useState<number>(0);
    const [current, setCurrent] = useState<number>(1);
    const [content, setContent] = useState<string>("");
    const [replyContentMap, setReplyContentMap] = useState<Record<number, string>>({});
    /** 当前展开的回复框对应的父级评论 ID（仅展示一个回复框） */
    const [activeReplyParentId, setActiveReplyParentId] = useState<number | null>(null);
    /** 解析与定位回复框的输入引用 */
    const replyInputRefs = useMemo<Record<number, TextAreaRef | null>>(() => ({} as Record<number, TextAreaRef | null>), []);

    /** 加载评论列表（包含二级） */
    const loadData = useCallback(async (page = current) => {
        setLoading(true);
        try {
            const res = await listPageUsingPost({
                questionId,
                current: page,
                pageSize,
                sortField: "createTime",
                sortOrder: "descend",
            });
            const pageData = (res.data || {}) as API.PageQuestionCommentVO_;
            setData(pageData.records || []);
            setTotal(pageData.total || 0);
            setCurrent(page);
        } catch (e: any) {
            message.error(e?.message || "加载评论失败");
        } finally {
            setLoading(false);
        }
    }, [questionId, pageSize, current]);

    useEffect(() => {
        loadData(1);
    }, [questionId]);

    /** 发表评论 */
    const handleSubmit = async () => {
        if (!isLoggedIn) {
            message.warning("请先登录再发表评论");
            window.location.href = `/user/login?redirect=${encodeURIComponent(window.location.href)}`;
            return;
        }
        if (!content || content.trim().length === 0) {
            message.warning("请输入评论内容");
            return;
        }
        setSubmitting(true);
        try {
            await addUsingPost({ questionId, content: content.trim() });
            setContent("");
            message.success("发布成功");
            loadData(1);
        } catch (e: any) {
            message.error(e?.message || "发布失败");
        } finally {
            setSubmitting(false);
        }
    };

    /** 删除评论（仅本人可删） */
    const handleDelete = async (id?: number, ownerId?: number) => {
        if (!id) return;
        if (!isLoggedIn || !loginUser?.id || loginUser.id !== ownerId) {
            message.warning("只能删除自己的评论");
            return;
        }
        Modal.confirm({
            title: "确认删除该评论？",
            okType: "danger",
            onOk: async () => {
                try {
                    await deleteUsingPost({ id });
                    message.success("已删除");
                    loadData();
                } catch (e: any) {
                    message.error(e?.message || "删除失败");
                }
            },
        });
    };

    /**
     * 发表评论的回复（仅支持二级）：
     * - parentId 始终指向顶层评论
     * - 内容中若以 @用户名 开头，则用于 UI 展示被 @ 的用户
     */
    const handleReplySubmit = async (parentId: number) => {
        const text = (replyContentMap[parentId] || "").trim();
        if (!isLoggedIn) {
            message.warning("请先登录再回复");
            window.location.href = `/user/login?redirect=${encodeURIComponent(window.location.href)}`;
            return;
        }
        if (!text) {
            message.warning("请输入回复内容");
            return;
        }
        setReplySubmittingId(parentId);
        try {
            // 后端返回新评论 ID，用于本地乐观更新
            const res = await addUsingPost({ questionId, content: text, parentId });
            const newId = (res as any)?.data as number | undefined;

            // 本地乐观更新：将新回复直接插入对应父评论的 children 列表
            setData((prev) => {
                const next = prev.map((p) => ({ ...p }));
                const parentIndex = next.findIndex((c) => c.id === parentId);
                if (parentIndex !== -1) {
                    const parent = next[parentIndex];
                    const newChild: API.QuestionCommentVO = {
                        id: newId,
                        parentId,
                        questionId,
                        content: text,
                        createTime: new Date().toISOString(),
                        updateTime: new Date().toISOString(),
                        userId: loginUser?.id,
                        user: {
                            id: loginUser?.id,
                            userName: loginUser?.userName,
                            userAvatar: loginUser?.userAvatar,
                        } as any,
                        children: [],
                    };
                    const children = Array.isArray(parent.children) ? [...parent.children, newChild] : [newChild];
                    next[parentIndex] = { ...parent, children } as API.QuestionCommentVO;
                }
                return next;
            });

            // 清空输入与收起回复框
            setReplyContentMap((prev) => ({ ...prev, [parentId]: "" }));
            setActiveReplyParentId(null);
            message.success("回复成功");
        } catch (e: any) {
            message.error(e?.message || "回复失败");
        } finally {
            setReplySubmittingId(null);
        }
    };

    /** 提取内容中的 @用户名（形如：@张三 空格 内容） */
    const extractAtName = (raw?: string): { atName?: string; pure?: string } => {
        const text = (raw || "").trim();
        const match = text.match(/^@([^\s@]{1,32})\s+(.*)$/);
        if (match) {
            return { atName: match[1], pure: match[2] };
        }
        return { pure: raw || "" };
    };

    /**
     * 展开并聚焦父级的回复框；如提供 targetUserName，则自动在输入框前置 @
     * - parentId：顶层评论 ID
     * - targetUserName：被回复的用户名（可能是父评论或某条子评论的作者）
     */
    const focusReply = (parentId?: number, targetUserName?: string) => {
        if (!parentId) return;
        // 展开指定父评论的回复框
        setActiveReplyParentId(parentId);

        // 若传入目标用户名：在未输入或输入未以 @ 开头时，自动补全 @用户名 空格
        setReplyContentMap((prev) => {
            const currentVal = prev[parentId] || "";
            const shouldPrefill = targetUserName && currentVal.trim().length === 0;
            return shouldPrefill
                ? { ...prev, [parentId]: `@${targetUserName} ` }
                : prev;
        });

        // 聚焦输入框
        const ref = replyInputRefs[parentId];
        setTimeout(() => ref?.focus?.(), 0);
    };

    return (
        <Card className="comment-section-card" title={<Space><MessageOutlined /> <span>评论区</span></Space>}>
            {/* 发布区 */}
            <div className="comment-editor">
                <Flex gap={12} align="start">
                    <Avatar size={40} src={loginUser?.userAvatar} alt={loginUser?.userName} />
                    <div className="editor-body">
                        <Input.TextArea
                            value={content}
                            onChange={(e) => setContent(e.target.value)}
                            placeholder={isLoggedIn ? "友善发言，文明讨论~" : "登录后参与评论"}
                            autoSize={{ minRows: 2, maxRows: 6 }}
                            disabled={!isLoggedIn}
                            maxLength={500}
                            showCount
                        />
                        <div className="editor-actions">
                            <Button type="primary" icon={<SendOutlined />} loading={submitting} onClick={handleSubmit} disabled={!isLoggedIn}>
                                发表
                            </Button>
                        </div>
                    </div>
                </Flex>
            </div>

            <Divider />

            {/* 列表区 */}
            <Skeleton loading={loading} active>
                {data.length === 0 ? (
                    <Empty description="还没有评论，快来抢沙发~" />
                ) : (
                    <List
                        itemLayout="vertical"
                        dataSource={data}
                        pagination={{
                            current,
                            total,
                            pageSize,
                            onChange: (page) => loadData(page),
                        }}
                        renderItem={(item) => {
                            const isOwner = loginUser?.id && item.userId === loginUser.id;
                            const parentNameMap: Record<number, string> = {};
                            parentNameMap[item.id!] = item.user?.userName || "匿名用户";

                            return (
                                <List.Item key={item.id}>
                                    <div className="comment-item">
                                        <div className="comment-header">
                                            <Avatar src={item.user?.userAvatar} />
                                            <Space size={8} className="comment-header-text">
                                                <span className="comment-username">{item.user?.userName || "匿名用户"}</span>
                                            </Space>
                                        </div>

                                        <div className="comment-bubble">
                                            <Typography.Paragraph className="comment-content">{item.content}</Typography.Paragraph>
                                        </div>

                                        <div className="comment-footer">
                                            <Space size={16}>
                                                <Tooltip title={dayjs(item.createTime).fromNow()}>
                                                    <span className="comment-time">{dayjs(item.createTime).format("YYYY-MM-DD HH:mm")}</span>
                                                </Tooltip>
                                                <Button
                                                    type="link"
                                                    size="small"
                                                    onClick={() => {
                                                        // 未登录：提示并跳转到登录页；已登录：打开回复框
                                                        if (!isLoggedIn) {
                                                            message.warning("请先登录再回复");
                                                            window.location.href = `/user/login?redirect=${encodeURIComponent(window.location.href)}`;
                                                            return;
                                                        }
                                                        focusReply(item.id, item.user?.userName);
                                                    }}
                                                >
                                                    回复
                                                </Button>
                                                {isOwner ? (
                                                    <Button type="link" size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(item.id, item.userId)}>
                                                        删除
                                                    </Button>
                                                ) : null}
                                            </Space>
                                        </div>

                                        {(item.children || []).length > 0 && (
                                            <div className="reply-list">
                                                {(item.children || []).map((child) => {
                                                    const isChildOwner = loginUser?.id && child.userId === loginUser.id;
                                                    // 从内容中解析 @ 用户名用于展示
                                                    const { atName, pure } = extractAtName(child.content);
                                                    return (
                                                        <div className="reply-item" key={child.id}>
                                                            <div className="reply-header">
                                                                <Avatar size={28} src={child.user?.userAvatar} />
                                                                <span className="comment-username">
                                                                    {child.user?.userName || "匿名用户"}{atName ? ` 回复：@${atName}` : ""}
                                                                </span>
                                                            </div>
                                                            <div className="reply-bubble">
                                                                <Typography.Paragraph className="comment-content">{pure || child.content}</Typography.Paragraph>
                                                            </div>
                                                            <div className="comment-footer">
                                                                <Space size={16}>
                                                                    <Tooltip title={dayjs(child.createTime).fromNow()}>
                                                                        <span className="comment-time">{dayjs(child.createTime).format("YYYY-MM-DD HH:mm")}</span>
                                                                    </Tooltip>
                                                                    <Button
                                                                        type="link"
                                                                        size="small"
                                                                        onClick={() => {
                                                                            // 未登录：提示并跳转到登录页；已登录：打开回复框
                                                                            if (!isLoggedIn) {
                                                                                message.warning("请先登录再回复");
                                                                                window.location.href = `/user/login?redirect=${encodeURIComponent(window.location.href)}`;
                                                                                return;
                                                                            }
                                                                            focusReply(item.id, child.user?.userName);
                                                                        }}
                                                                    >
                                                                        回复
                                                                    </Button>
                                                                    {isChildOwner ? (
                                                                        <Button type="link" size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(child.id, child.userId)}>
                                                                            删除
                                                                        </Button>
                                                                    ) : null}
                                                                </Space>
                                                            </div>
                                                        </div>
                                                    );
                                                })}
                                            </div>
                                        )}

                                        {/* 回复编辑框 */}
                                        <Row gutter={12} className="reply-editor-row">
                                            <Col span={24}>
                                                {activeReplyParentId === item.id ? (
                                                    <>
                                                        <Input.TextArea
                                                            className="reply-editor-input"
                                                            ref={(r) => {
                                                                replyInputRefs[item.id!] = r;
                                                            }}
                                                            value={replyContentMap[item.id!] || ""}
                                                            onChange={(e) => setReplyContentMap((prev) => ({ ...prev, [item.id!]: e.target.value }))}
                                                            placeholder={isLoggedIn ? "回复一下..." : "登录后可回复"}
                                                            autoSize={{ minRows: 1, maxRows: 4 }}
                                                            disabled={!isLoggedIn}
                                                            maxLength={300}
                                                            showCount
                                                        />
                                                        <div className="reply-actions">
                                                            <Space>
                                                                <Button
                                                                    size="small"
                                                                    onClick={() => setActiveReplyParentId(null)}
                                                                >
                                                                    取消
                                                                </Button>
                                                                <Button
                                                                    size="small"
                                                                    type="primary"
                                                                    icon={<SendOutlined />}
                                                                    loading={replySubmittingId === item.id}
                                                                    onClick={() => handleReplySubmit(item.id!)}
                                                                    disabled={!isLoggedIn}
                                                                >
                                                                    回复
                                                                </Button>
                                                            </Space>
                                                        </div>
                                                    </>
                                                ) : null}
                                            </Col>
                                        </Row>
                                    </div>
                                </List.Item>
                            );
                        }}
                    />
                )}
            </Skeleton>
        </Card>
    );
};

export default CommentSection;


